package com.yunchuang.controller.user;

import cn.hutool.core.util.StrUtil;
import com.wf.captcha.utils.CaptchaUtil;
import com.yunchuang.common.BaseResult;
import com.yunchuang.common.ResultUtil;
import com.yunchuang.model.dto.UserLoginDto;
import com.yunchuang.model.pojo.User;
import com.yunchuang.service.FileMonitorService;
import com.yunchuang.service.UserService;
import com.yunchuang.service.impl.UserServiceImpl;
import com.yunchuang.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

import static com.yunchuang.constant.CommonConstant.ERROR_CODE;
import static com.yunchuang.constant.CommonConstant.SERVICE_ERROR_CODE;

/**
 * 用户登录接口
 *
 * @author ItJiange
 * @date 2023/10/21
 */
@WebServlet("/user/login")
public class UserLoginController extends HttpServlet {
    private final Logger logger= LoggerFactory.getLogger("logback");
    private FileMonitorService fileMonitorService = new FileMonitorService();
    private final UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取请求参数
        BufferedReader reader = req.getReader();
        String jsonObject = reader.readLine();
        // 解析为 User 对象
        UserLoginDto userLoginDto = JSONUtils.jsonToObject(jsonObject, UserLoginDto.class);
        String username = userLoginDto.getUserName();
        String password = userLoginDto.getPassword();
        String verCode = userLoginDto.getVerCode();
        // 2. 校验
        if (StrUtil.hasEmpty(username, password, verCode)) {
            JSONUtils.writeOutJSON(ResultUtil.error("登录信息为空！请重新登录"), resp);
            return;
        }
        if (!CaptchaUtil.ver(verCode, req)) {
            CaptchaUtil.clear(req);
            JSONUtils.writeOutJSON(ResultUtil.error("验证码不正确！请重新登录！"), resp);
            return;
        }
        // 获取登录结果
        BaseResult baseResult = userService.userLogin(username, password, req);
        if (ERROR_CODE == baseResult.getCode()) {
            JSONUtils.writeOutJSON(baseResult, resp);
            return;
        }
        JSONUtils.writeOutJSON(baseResult, resp);
    }

    @Override
    public void init() throws ServletException {
        fileMonitorService.startFileMonitor();
    }

    @Override
    public void destroy() {
        fileMonitorService.stopFileMonitor();
    }
}
